home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / ULARN.ARJ / ULARN.TAR / ularn / fortune.c < prev    next >
C/C++ Source or Header  |  1989-10-25  |  2KB  |  67 lines

  1. /* fortune.c */
  2. #include "header.h"
  3. /*
  4.  *    function to return a random fortune from the fortune file
  5.  */
  6. static char *base=0;    /* pointer to the fortune text */
  7. static char **flines=0;    /* array of pointers to each fortune */
  8. static int fd=0;        /* true if we have load the fortune info */
  9. static int nlines=0;    /* # lines in fortune database */
  10.  
  11. char *fortune(file)
  12. char *file;
  13. {
  14.     register char *p;
  15.     register int lines,tmp;
  16.     struct stat stat;
  17.     char *malloc();
  18.  
  19.     if (fd==0) {
  20.         if ((fd=open(file,O_RDONLY)) < 0)    /* open the file */
  21.             return(0); /* can't find file */
  22.  
  23.         /* find out how big fortune file is and get memory for it */
  24.         stat.st_size = 16384;
  25.         if ((fstat(fd,&stat) < 0) || ((base=malloc(1+stat.st_size)) == 0))
  26.         {
  27.             close(fd); 
  28.             fd= -1; 
  29.             free((char*)base); 
  30.             return(0);     /* can't stat file */
  31.         }
  32.  
  33.         /* read in the entire fortune file */
  34.         if (read(fd,base,stat.st_size) != stat.st_size) {
  35.             close(fd); 
  36.             fd= -1; 
  37.             free((char*)base); 
  38.             return(0);     /* can't read file */
  39.         }
  40.         close(fd);  
  41.         base[stat.st_size]=0;    /* final NULL termination */
  42.  
  43.     /* count up all the lines (and NULL terminate) to know memory needs */
  44.         for (p=base,lines=0; p<base+stat.st_size; p++) /* count lines */
  45.             if (*p == '\n') *p=0,lines++;
  46.         nlines = lines;
  47.  
  48.         /* get memory for array of pointers to each fortune */
  49.         if ((flines=(char**)malloc(nlines*sizeof(char*))) == 0) {
  50.             free((char*)base); 
  51.             fd= -1; 
  52.             return(0); /* malloc() failure */
  53.         }
  54.  
  55.         /* now assign each pointer to a line */
  56.         for (p=base,tmp=0; tmp<nlines; tmp++) {
  57.             flines[tmp]=p;  
  58.             while (*p++); /* advance to next line */
  59.         }
  60.     }
  61.  
  62.     if (fd > 2)    /* if we have a database to look at */
  63.         return(flines[rund((nlines<=0)?1:nlines)]);
  64.     else 
  65.         return(0);
  66. }
  67.